package com.websocet.controller;

import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author: 陈玉鹏
 * @Description: TODO
 * @DateTime: 2023/4/20 19:38
 */
@RestController
public class TestComplateFuture {

    @SneakyThrows
    @GetMapping("/testCom")
    public long test() {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("主线程开始"+dateformat.format(System.currentTimeMillis()));
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        CompletableFuture<Long> stringCompletableFuture1 = CompletableFuture.supplyAsync(() -> {
            return com1();
        });
        CompletableFuture<Long> stringCompletableFuture2 = CompletableFuture.supplyAsync(() -> {
            return com2();
        });
        CompletableFuture.allOf(stringCompletableFuture1, stringCompletableFuture2).get();

        System.out.println("主线程结束"+dateformat.format(System.currentTimeMillis()));
        return 0;
    }

    public long com1() {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        System.out.println("异步线程1开始"+dateformat.format(System.currentTimeMillis()));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("异步线程1结束"+dateformat.format(System.currentTimeMillis()));
        return 3000;
    }
    public long com2() {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        System.out.println("异步线程2开始"+dateformat.format(System.currentTimeMillis()));
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("异步线程2结束"+dateformat.format(System.currentTimeMillis()));
        return 3000;
    }
}
